<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card shadow="always">
      <el-alert
      title="部分操作仅限系统管理员账户（admin）可用"
      type="info"
      v-show="$getCookie('is_admin') != 1"
      :closable="false"
      center
      show-icon>
    </el-alert>
      <!-- 用户搜索功能 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请输入内容" 
          v-model="queryInfo.query" 
          @keyup.enter.native="getUserData" 
          clearable
          @clear="getUserData">
            <el-button slot="append" icon="el-icon-search" @click="getUserData"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="dialogVisible = true" :disabled="$getCookie('is_admin') != 1">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 用户表单 -->
      <el-table
      :data="userList"
      style="width: 100%"
      border
      stripe>
      <el-table-column type="index" label="#" ></el-table-column>
      <el-table-column prop="username" label="姓名"></el-table-column>
      <el-table-column prop="email" label="邮箱"></el-table-column>
      <el-table-column prop="mobile" label="电话"></el-table-column>
      <el-table-column prop="role_name" label="权限"></el-table-column>
      <el-table-column prop="mg_state" label="状态">
        <template v-slot="scope">
          <el-switch v-model="scope.row.mg_state"
          @change="userStateChange(scope.row)">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180">
        <template v-slot="scope">
          <el-button type="primary" icon="el-icon-edit" size="mini" :disabled="$getCookie('is_admin') != 1" @click="showDialog(scope.row.id)"></el-button>
          <el-button type="danger" icon="el-icon-delete" size="mini" :disabled="$getCookie('is_admin') != 1" @click="deleteUser(scope.row.id)"></el-button>
          <el-tooltip effect="dark" content="分配角色" placement="top-end" :enterable="false">
            <el-button type="warning" icon="el-icon-setting" size="mini" :disabled="$getCookie('is_admin') != 1" @click="setRole(scope.row)"></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <!-- 页码条 -->
    <el-pagination
      @size-change="handleSizeChange" 
      @current-change="handleCurrentChange"
      :current-page="queryInfo.pagenum"
      :page-sizes="[3, 6, 8, 10]"
      :page-size="queryInfo.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>
    </el-card>
    <!-- 添加用户的对话框 -->
    <el-dialog
      title="添加用户"
      :visible.sync="dialogVisible"
      width="50%"
      @close="dialogClose">
      <el-form :model="userForm" :rules="userFormRule" :status-icon="true" ref="userForm">
        <el-form-item label="用户名" label-width="70px" prop="username">
          <el-input v-model="userForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" label-width="70px" prop="password">
          <el-input v-model="userForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" label-width="70px" prop="email">
          <el-input v-model="userForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" label-width="70px" prop="mobile">
          <el-input v-model="userForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
     <!-- 修改用户的对话框 -->
    <el-dialog
      title="修改用户数据"
      :visible.sync="editDialogVisible"
      width="50%" 
      @close="editClose">
      <el-form :model="editForm" :rules="editFormRule" :status-icon="true" ref="editForm">
        <el-form-item label="用户名" label-width="70px">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" label-width="70px" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" label-width="70px" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUser(editForm)">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 给用户分配角色对话框 -->
    <el-dialog
      title="分配角色"
      :visible.sync="setRoleDialogVisible"
      width="50%" 
      @close="newRoleId = ''">
      <p>当前用户：{{userInfo.username}}</p>
      <p>当前角色：{{userInfo.role_name}}</p>
      <p>分配新角色：
        <el-select v-model="newRoleId" placeholder="请选择">
          <el-tooltip 
          v-for="item in roleList"
          :key="item.id" 
          :content="item.roleDesc"
          placement="right"
          effect="light">
            <el-option :label="item.roleName" :value="item.id"></el-option>
          </el-tooltip>
        </el-select>
      </p>
      <span slot="footer">
        <el-button @click="setRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRole">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import {getMenusList, getHomeData} from 'network/home.js';

  export default {
    name: 'Users',
    data() {
      return {
        queryInfo: {
          // 所需查询的字符串
          query: '',
          // 当前数据在第几页
          pagenum: 1,
          // 每页展示多少条数据
          pagesize: 3
        },
        // 对获取的用户数据进行保存
        userList: [],
        // 一共有多少条数据
        total: 0,
        dialogVisible: false,
        userForm: {
          username: '',
          password: '',
          email: '',
          mobile: ''
        },
        userFormRule: {
          username: [
            { required: true, message: '请输入用户名', trigger: 'blur' },
            { min: 3, max: 6, message: '用户名应当为3~6个字符', trigger: 'blur'}
          ],
          password: [
            { required: true, message: '请输入密码', trigger: 'blur' },
            { min: 6, max: 12, message: '密码应当为6~12个字符', trigger: 'blur'}
          ],
          email: [
            { required: true, message: '请输入邮箱', trigger: 'blur' },
          ],
          mobile: [
            { required: true, message: '请输入手机号码', trigger: 'blur' },
          ],
        },
        // 修改用户相关变量
        editDialogVisible: false,
        editForm: {},
        editFormRule: {
          email: [
            { required: true, message: '请输入邮箱', trigger: 'blur' },
          ],
          mobile: [
            { required: true, message: '请输入手机号码', trigger: 'blur' },
          ],
        },
        // 是否打开分配角色对话框
        setRoleDialogVisible: false,
        // 保存用户信息
        userInfo: {},
        // 保存所有角色列表
        roleList: [],
        // 所选的角色
        newRoleId: ''
      }
    },
    components: {
      
    },
    created() {
      this.getUserData();
    },
    methods: {
      // 获取用户的数据
      async getUserData() {
        try {
          let res = await getHomeData({ url: '/users',params: this.queryInfo })
          this.total = res.data.total;
          this.userList = res.data.users;
        } catch (error) {
          // console.log(error);
          this.$message.error(new Error(error.meta.msg || error))
        };
        
        {
          // getHomeData({
        //   url: '/users',
        //   params: this.queryInfo
        // })
        // .then(res => {
        //   // console.log(res);
        //   this.total = res.data.total;
        //   this.userList = res.data.users;
        // })
        // .catch(rej => {
        //   this.$message.error(new Error(rej.meta.msg))
        // })
        }
      },
      // 监听当前页面显示多少条数据的改变
      handleSizeChange(newSize) {
        this.queryInfo.pagesize = newSize;
        this.getUserData();
      },
      // 监听页码的改变
      handleCurrentChange(newPage) {
        this.queryInfo.pagenum = newPage;
        this.getUserData();
      },
      // 实现更改用户状态的功能
      async userStateChange(user_info) {
        try {
          let res = await getHomeData({ url: `/users/${user_info.id}/state/${user_info.mg_state}` }, 'put')
          if(res.meta.status !== 200) {
            return this.$message({
              type: 'error',
              message: res.meta.msg
            })
          }
          this.$message.success(res.meta.msg)
        } catch (error) {
          this.$message.error('更改状态失败')
        }

        {
          // getHomeData({
        //   url: `/users/${user_info.id}/state/${user_info.mg_state}`
        // }, 'put')
        // .then(res => {
        //   if(res.meta.status !== 200) {
        //     return this.$message({
        //       type: 'error',
        //       message: res.meta.msg
        //     })
        //   }
        //   this.$message.success(res.meta.msg)
        // })
        // .catch(rej => {
        //   this.$message.error('更改状态失败')
        // })
        }
      },
      // 清空添加用户表单的功能
      dialogClose() {
        this.$refs.userForm.resetFields();
      },
      // 添加用户功能
      addUser() {
        this.$refs.userForm.validate(async valid => {
          if(!valid) return; 
          let user = this.$getCookie('user_arr') || []
          user.push({username: this.userForm.username, password: this.userForm.password})
          this.$setCookie('user_arr', user)

          try {
            let res = await getHomeData({ url: '/users', data: this.userForm }, 'post')
            if(res.meta.status !== 201) return this.$message.error(new Error(res.meta.msg));
            this.dialogVisible = false;
            this.$message.success(res.meta.msg);
            this.getUserData();
          } catch (error) {
            this.$message.error(new Error('添加用户失败'))
          }

          // 发起添加用户的网络请求
          {
          //   getHomeData({
          //   url: '/users',
          //   data: this.userForm
          // }, 'post')
          // .then(res => {
          //   if(res.meta.status !== 201) return this.$message.error(new Error(res.meta.msg));
          //   this.dialogVisible = false;
          //   this.$message.success(res.meta.msg);
          //   this.getUserData();
          // })
          // .catch(rej => this.$message.error(new Error('添加用户失败')))
          }
        })
      },
      // 编辑用户的数据获取
      async showDialog(id) {
        try {
          let res = await getHomeData({ url: `users/${id}` })
          this.editForm = res.data
          this.editDialogVisible = true;
        } catch (error) {
          this.$message.error(new Error('获取用户信息失败'))
        }

        {
        //   getHomeData({
        //   url: `users/${id}`
        // })
        // .then(res => {
        //   this.editForm = res.data
        // })
        // .catch(() => this.$message.error(new Error('获取用户信息失败')))
        // this.editDialogVisible = true;
        }
      },
      // 编辑用户的功能的实现
      editUser(editForm) {
        this.$refs.editForm.validate(async valid => {
          if(!valid) return; 
          try {
            this.editDialogVisible = false;
            let res = await getHomeData({
              url: `users/${editForm.id}`,
              data: {
                email: editForm.email,
                mobile: editForm.mobile
              }
            }, 'put')
          if(res.meta.status !== 200) return this.$message.error(new Error(res.meta.msg));
            this.$message.success(res.meta.msg);
            this.getUserData()
          } catch (error) {
            this.$message.error('编辑失败');
          }

          {
            // getHomeData({
          //   url: `users/${editForm.id}`,
          //   data: {
          //     email: editForm.email,
          //     mobile: editForm.mobile
          //   }
          // }, 'put')
          // .then(res => {
          //   if(res.meta.status !== 200) return this.$message.error(new Error(res.meta.msg));
          //   this.$message.success(res.meta.msg);
          //   this.getUserData()
          // })
          // this.editDialogVisible = false;
          }
        })
      },
      // 清空编辑用户表单的数据
      editClose() {
        this.$refs.editForm.resetFields();
      },
      // 实现删除用户的操作
      async deleteUser(id) {
        let username = this.userList.find(v => v.id === id).username;
        try {
          await this.$confirm('此操作将永久删除用户, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
          let res = await getHomeData({ url: `users/${id}` }, 'delete')
          let user = this.$getCookie('user_arr') || []
          let index = user.findIndex(v => v.username === username)
          user.splice(index, 1)
          this.$setCookie('user_arr', user)
          this.$message({
            type: 'success',
            message: res.meta.msg
          })
          this.getUserData()
          // console.log(val);
        } catch (error) {
          // console.log(error);
          if(error == 'cancel')  return this.$message({ type: 'info', message: '已经取消删除'});
          this.$message({ type: 'error', message: new Error('删除失败') })
        }

        {
          // this.$confirm('此操作将永久删除用户, 是否继续?', '提示', {
        //   confirmButtonText: '确定',
        //   cancelButtonText: '取消',
        //   type: 'warning'
        // })
        // .then(() => {
        //   return getHomeData({
        //     url: `users/${id}`
        //   }, 'delete')
        // })
        // .catch(() => {
        //   this.$message({
        //     type: 'info',
        //     message: '已经取消删除'
        //   })
        //   return new Promise(() => {});
        // })
        // .then(res => {
        //     let user = this.$getCookie('user_arr') || []
        //     let index = user.findIndex(v => v.username === username)
        //     user.splice(index, 1)
        //     this.$setCookie('user_arr', user)
        //     this.$message({
        //       type: 'success',
        //       message: res.meta.msg
        //     })
        //     this.getUserData()
        //   })
        //   .catch(() => {
        //     this.$message({
        //       type: 'error',
        //       message: new Error('删除失败')
        //     })
        //     return new Promise(() => {});
        //   })
        }
      },
      // 分配角色
      async setRole(info) {
        this.userInfo = info;
        try {
          let res = await getHomeData({ url: 'roles' })
          this.roleList = res.data
          this.setRoleDialogVisible = true;
        } catch (error) {
          this.$message.error(new Error('获取角色列表失败'))
        }
        {
        //   getHomeData({
        //   url: 'roles'
        // })
        // .then(res => {
        //   this.roleList = res.data
        // })
        // .catch(() => this.$message.error(new Error('获取角色列表失败')))
        // this.setRoleDialogVisible = true;
        }
      },
      // 保存所要分配的角色
      async saveRole() {
        if(this.newRoleId === '') return this.$message.warning('请选择需要分配的角色');

        try {
          let res = await getHomeData({
            url: `users/${this.userInfo.id}/role`,
            data: {
              rid: this.newRoleId
            }
          }, 'put')
          if(res.meta.status !== 200) {
          return this.$message({
            type: 'error',
            message: res.meta.msg
          })
          }
          this.getUserData()
          this.$message({
            type: 'success',
            message: res.meta.msg
          })
          this.setRoleDialogVisible = false
        } catch (error) {
          this.$message.error(new Error('分配角色失败'))
        }

        {
          // getHomeData({
        //   url: `users/${this.userInfo.id}/role`,
        //   data: {
        //     rid: this.newRoleId
        //   }
        // }, 'put')
        // .then(res => {
        //   if(res.meta.status !== 200) {
        //     return this.$message({
        //       type: 'error',
        //       message: res.meta.msg
        //     })
        //   }
        //   this.getUserData()
        //   this.$message({
        //       type: 'success',
        //       message: res.meta.msg
        //     })
        // })
        // .catch(() => this.$message.error(new Error('分配角色失败')))
        // this.setRoleDialogVisible = false
        }
      }
    },
  }
</script>

<style scoped>
  .el-row, .el-table  {
    margin-bottom: 15px;
  }
  .el-alert {
    margin-bottom: 20px;
  }
</style>